<template>
  <div class="timeout-picker">
    <el-popover
      v-model:visible="showPicker"
      trigger="click"
      placement="bottom"
      :width="240"
      popper-class="timeout-picker-popover"
    >
      <template #reference>
        <div class="input-wrapper">
          <el-input v-model="displayValue" @change="handleInputChange" placeholder="如：1d 4h 30m">
            <template #suffix>
              <el-icon class="picker-trigger">
                <Clock />
              </el-icon>
            </template>
          </el-input>
        </div>
      </template>
      <div class="picker-panel">
        <div class="panel-row">
          <span class="label">天数</span>
          <div class="number-input">
            <el-input-number
              v-model="days"
              :min="0"
              :controls="true"
              @change="handleNumberChange('d')"
              size="small"
            />
          </div>
        </div>
        <div class="panel-row">
          <span class="label">小时</span>
          <div class="number-input">
            <el-input-number
              v-model="hours"
              :min="0"
              :max="23"
              :controls="true"
              @change="handleNumberChange('h')"
              size="small"
            />
          </div>
        </div>
        <div class="panel-row">
          <span class="label">分钟</span>
          <div class="number-input">
            <el-input-number
              v-model="minutes"
              :min="0"
              :max="59"
              :controls="true"
              @change="handleNumberChange('m')"
              size="small"
            />
          </div>
        </div>
        <div class="panel-footer">
          <el-button size="small" @click="clearValue">清空</el-button>
          <el-button size="small" type="primary" @click="confirmValue">确定</el-button>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { Clock } from '@element-plus/icons-vue'

const props = defineProps<{
  modelValue: string
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void
}>()

const showPicker = ref(false)
const days = ref(0)
const hours = ref(0)
const minutes = ref(0)
const displayValue = ref(props.modelValue)
const iso8601Value = ref('')

// 解析时间字符串
const parseTimeString = (timeStr: string) => {
  // 检查是否是ISO8601格式
  if (timeStr.startsWith('P')) {
    // ISO8601格式解析
    const daysMatch = timeStr.match(/P(?:(\d+)D)?/)
    const hoursMatch = timeStr.match(/T(?:.*?(\d+)H)?/)
    const minutesMatch = timeStr.match(/T(?:.*?(\d+)M)?/)

    days.value = daysMatch && daysMatch[1] ? parseInt(daysMatch[1]) : 0
    hours.value = hoursMatch && hoursMatch[1] ? parseInt(hoursMatch[1]) : 0
    minutes.value = minutesMatch && minutesMatch[1] ? parseInt(minutesMatch[1]) : 0
  } else {
    // 用户友好格式解析
    const d = timeStr.match(/(\d+)d/)?.[1] || '0'
    const h = timeStr.match(/(\d+)h/)?.[1] || '0'
    const m = timeStr.match(/(\d+)m/)?.[1] || '0'

    days.value = parseInt(d)
    hours.value = parseInt(h)
    minutes.value = parseInt(m)
  }
}

// 格式化时间为用户友好的字符串
const formatTime = () => {
  const parts = []
  if (days.value > 0) parts.push(`${days.value}d`)
  if (hours.value > 0) parts.push(`${hours.value}h`)
  if (minutes.value > 0) parts.push(`${minutes.value}m`)
  return parts.join(' ')
}

// 转换为ISO8601时间持续格式
const formatISO8601Duration = () => {
  // 如果所有值都为0，返回空字符串
  if (days.value === 0 && hours.value === 0 && minutes.value === 0) {
    return ''
  }

  let result = 'P'
  if (days.value > 0) {
    result += `${days.value}D`
  }

  // 添加时间部分（如果有小时或分钟）
  if (hours.value > 0 || minutes.value > 0) {
    result += 'T'
    if (hours.value > 0) {
      result += `${hours.value}H`
    }
    if (minutes.value > 0) {
      result += `${minutes.value}M`
    }
  }

  return result
}

// 监听输入值变化
watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue) {
      // 如果是ISO8601格式，先解析，然后更新显示值为用户友好格式
      if (newValue.startsWith('P')) {
        iso8601Value.value = newValue
        parseTimeString(newValue)
        displayValue.value = formatTime()
      } else {
        // 如果是用户友好格式，直接显示
        displayValue.value = newValue
        parseTimeString(newValue)
        iso8601Value.value = formatISO8601Duration()
      }
    } else {
      displayValue.value = ''
      iso8601Value.value = ''
      days.value = 0
      hours.value = 0
      minutes.value = 0
    }
  },
  { immediate: true },
)

// 处理数字输入变化
const handleNumberChange = (unit: 'd' | 'h' | 'm') => {
  if (unit === 'h') {
    hours.value = Math.min(Math.max(hours.value, 0), 23)
  } else if (unit === 'm') {
    minutes.value = Math.min(Math.max(minutes.value, 0), 59)
  }
  updateDisplayValue()
}

// 更新显示值
const updateDisplayValue = () => {
  const friendlyFormat = formatTime()
  const iso8601Format = formatISO8601Duration()

  // 更新显示值（用户友好格式）
  displayValue.value = friendlyFormat
  iso8601Value.value = iso8601Format

  // 发送ISO8601格式的值给父组件
  emit('update:modelValue', iso8601Format)
}

// 处理输入框直接输入
const handleInputChange = () => {
  parseTimeString(displayValue.value)
  updateDisplayValue()
}

// 更新数值
const updateValue = (unit: 'd' | 'h' | 'm', delta: number) => {
  if (unit === 'd') {
    days.value = Math.max(0, days.value + delta)
  } else if (unit === 'h') {
    hours.value = Math.min(Math.max(0, hours.value + delta), 23)
  } else {
    minutes.value = Math.min(Math.max(0, minutes.value + delta), 59)
  }
  updateDisplayValue()
}

// 清空值
const clearValue = () => {
  days.value = 0
  hours.value = 0
  minutes.value = 0
  updateDisplayValue()
  showPicker.value = false
}

// 确认选择
const confirmValue = () => {
  updateDisplayValue()
  showPicker.value = false
}

// El-popover会自动处理点击外部关闭的逻辑，不需要手动添加事件监听
</script>

<style lang="scss" scoped>
.timeout-picker {
  position: relative;
  width: 100%;

  .input-wrapper {
    width: 100%;
  }

  .picker-trigger {
    cursor: pointer;
    color: #999;

    &:hover {
      color: #409eff;
    }
  }

  .picker-panel {
    padding: 8px 0;

    .panel-row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;
      padding: 0 8px;

      .label {
        font-size: 13px;
        color: #606266;
        margin-right: 12px;
      }

      .number-input {
        flex: 1;
      }
    }

    .panel-footer {
      display: flex;
      justify-content: flex-end;
      margin-top: 12px;
      padding: 0 8px;
      gap: 8px;
    }
  }
}

:deep(.timeout-picker-popover) {
  padding: 12px;
  min-width: 240px;
}
</style>
